﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharePointOfView.WebControls;
using System.IO;
using Microsoft.SharePoint;
using System.Web.UI.WebControls.WebParts;
using System.ComponentModel;

namespace SharePointOfView.Samples.WebControls
{
    /// <summary>Sample WebPart used to show how to use WebPartBase.</summary>
    /// <remarks>You should be logged as a site administrator to view WebPartBase full behavior.</remarks>
    public class RandomExceptionWebPart : WebPartBase
    {
        /// <summary>Generate a random exception so as to use WebPartBase error handling</summary>
        /// <param name="writer">HTML Text writer</param>
        protected override void RenderWebPart(System.Web.UI.HtmlTextWriter writer)
        {
            base.RenderWebPart(writer);

            Random rand = new Random();
            object[] exTab = new object[2];
            SPSite site = null;

            switch (rand.Next(4))
            {
                case 1:
                    // Generate an IndexOutOfRangeException
                    // http://msdn.microsoft.com/en-us/library/system.indexoutofrangeexception.aspx
                    exTab[3] = 0;
                    break;
                case 2:
                    // Generate a FileNotFoundException
                    // http://msdn.microsoft.com/en-us/library/system.io.filenotfoundexception.aspx
                    FileStream fs = File.Open(exTab.ToString(), FileMode.Open);
                    break;
                case 3:
                    // Generate a UriFormatException
                    // http://msdn.microsoft.com/en-us/library/system.uriformatexception.aspx
                    site = new SPSite(exTab.ToString());
                    break;
                default:
                    throw new Exception("An auto generated error has occured. Please, refresh the page to try getting a new error.");
            }
        }
    }
}
